<?
	require_once('model/User.php');
	require_once('model/Question.php');
	require_once('model/Car.php');
	require_once('model/News.php');
	

	final class NewsController extends Controller {

		public function News() {
			$this->headers['Content-type'] = 'text/html';
			$this->stylesheet = 'News';
			
			//News::CreateNewsFish(12);

			
			$this->page->MountSource(Question:: FAQ(2));
			
			$news_on_page = 6;
			$page = (int)$this->params['page'];
			$offset = 0;
			if($page > 0)
				$offset = ($page-1)*$news_on_page;
			
			$this->page->MountSource(News::NewsByCount($news_on_page,$offset));
						
		}
	

		public function UnknownRoute() {
			$this->params['ERROR'] = true;
		}
		
		public function ShowEditor(){
			
			if(CurrentUserIsAdmin()){
				if(isset($this->params['news_id'])){
				 	$news_id = (int)$this->params['news_id'];
				 	
				 	$news_post = new News($news_id);
				 	$news_post->Load();
				 	$this->styleparams['title'] = $news_post->Title();
				 	$this->styleparams['announce'] = $news_post->Announce();
				 	$this->styleparams['content'] = $news_post->Content();
				 	
					$this->styleparams['news_id'] = $news_id;
					$_SESSION['user_files_upload_path']='/media/news/'.$news_id.'/';
					
				}
				else{
					
					$_SESSION['user_files_upload_path']='/fcktemp/';	
					clear_dir($_SERVER['DOCUMENT_ROOT'].'/fcktemp');
					
				}
				
				$this->stylesheet = 'Editor';
				
			}
			else $this->Redirect('/');
		}
		
		
		
		public function Check() {
			//print_r($_FILES);
			
			
			if(!CurrentUserIsAdmin()){
				$this->Redirect('/');
				return ;
			}

			
			$news_id = (int)$this->request['news_id'];
			if($news_id<1) $obj = new News();
			else{
				$obj = new News($news_id);
				$obj->Load();				
		
			}
			$obj->Title(mes($this->request['title']));
			$obj->Announce(mes($this->request['article']));
			$obj->Content(CutRN($this->request['editor']));
			$obj->Save();
			if($news_id<1){
				copy_dir2($_SERVER['DOCUMENT_ROOT'].'/fcktemp', $_SERVER['DOCUMENT_ROOT'].'/media/news/'.$obj->Id());
				
				$obj->Content(str_replace('/fcktemp/','/media/news/'.$obj->Id().'/', $obj->Content()));
				
				$obj->Save();
			}

			//getting title image
			//TODO check filetype and size
			//if have old, delete
			$new_path = $_SERVER['DOCUMENT_ROOT'].'/media/news/'.$obj->Id().'/title_news.jpg';
			if($_FILES['title_img']['error'] == UPLOAD_ERR_OK){
				if(is_file($new_path)) unlink($new_path);
				move_uploaded_file($_FILES['title_img']['tmp_name'], $new_path);
			}
			else {
				//TODO error no image
			}
			
			$this->Redirect('/news');
		}			
		
		public function Remove(){
			if(!CurrentUserIsAdmin()){
				$this->Redirect('/');
				return ;
			}
			$news_id = (int)$this->params['news_id'];
			$obj = new News($news_id);			
			$obj->Remove();
			$this->Redirect('/news');
			
			$news_dir = $_SERVER['DOCUMENT_ROOT'].'/media/news/'.$news_id;
			if(is_dir($news_dir))
				del_dir($news_dir);
		}

	}
?>